import global, { VERSION, WS_Path } from "../global";
import storage from "../util/storage";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Loading extends cc.Component {

    @property(cc.Sprite)
    Sprite_progress:cc.Sprite = null;   //进度条填充

    value_progress:number = 0;      //当前加载到的程度

    onLoad(){
        //json转对象
        cc.resources.loadDir("json",this.onComplete.bind(this));
        //读取本地存储信息
        this.getLocalStorage();
        //场景预加载  +.6
        this.preloadScene();
        //WebSocket初始化  +.4
        this.webSocketInit();
    }

    /**
     * 读取json
     */
    onComplete(err:object, assets) {
        if (err) {
            console.log(err);
            return;
        } else {
            let asset = assets[1] as cc.JsonAsset;
            global.temp.arrSkill = asset.json;
            cc.assetManager.releaseAsset(assets);
        } 
    }

    /**
     * 读取本地存储信息
     */
    getLocalStorage(){
        let data = storage.get("data",true);
        if(data){
            global.data = data;
        }
    }


    /**
     * 场景预加载
     */
    preloadScene(){
        cc.director.preloadScene("game",()=>{
            this.value_progress+=.2;
            this.showProgress();
        });
        cc.director.preloadScene("index",()=>{
            this.value_progress+=.1;
            this.showProgress();
        });
        cc.director.preloadScene("replay",()=>{
            this.value_progress+=.2;
            this.showProgress();
        });
        cc.director.preloadScene("studySkill",()=>{
            this.value_progress+=.1;
            this.showProgress();
        });
    }

    /**
     * WebScoket
     */
    webSocketInit(){
        global.websocket = new WebSocket(WS_Path);
        global.webSocketInit()
        global.websocket.onopen = () => {
            this.value_progress+=.4;
            this.showProgress();
        }
        global.websocket.onerror = () => {
            global.persist.tip("服务器无法连接")
        }
    }


    /**
     * 进度加载动画
     */
    is_over:boolean = false;    //防止重复执行
    showProgress(){
        cc.tween(this.Sprite_progress).to(1,{fillRange:this.value_progress}).call(()=>{
            if(this.value_progress>=.99&&!this.is_over){
                this.is_over = true;
                cc.director.loadScene("index");
            }
        }).start();
    }
}
